<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- layout -->
      <el-row>
        <!-- 按钮 -->
        <el-col>
          <el-button type="primary" @click="addRoleBtn">添加成员</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom',index1 === 0?'bdtop':'','vcenter']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0?'':'bdtop','vcenter']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(scope.row)"
            >删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限--Dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <!-- node-key 三级权限选中，一二级同步勾选 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="setAddRoleDialogClosed"
    >
      <el-form :model="queryForm" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="queryForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:" prop="roleDesc">
          <el-input v-model="queryForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddRoleBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightDialogVisible: false, // 权限对话框
      addRoleDialogVisible: false, // 角色对话框
      addRoleRules: {
        roleName: {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        roleDesc: {
          required: true,
          message: '请输入角色描述',
          trigger: 'blur'
        }
      },
      queryForm: {
        roleName: '',
        roleDesc: ''
      },
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中 数组 default-checked-keys
      defKeys: [],
      // 当前即将分配权限的id
      roleId: ''
    }
  },
  methods: {
    addRoleBtn() {
      this.addRoleDialogVisible = true
    },
    // 监听对话框关闭事件
    setAddRoleDialogClosed() {
      console.log('对话框关闭')
      this.$refs.addRoleRef.resetFields()
    },
    // 确定按钮
    confirmAddRoleBtn() {
      console.log('确定添加角色')
      console.log(this.queryForm)
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.get('/roles', {
          params: this.queryForm
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(`${res.meta.msg}`)
        }
        this.$message.success(`${res.meta.msg}`)
        console.log('新增成功')
        this.$refs.addRoleRef.resetFields()
        this.addRoleDialogVisible = false
      })
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配失败!')
      }
      this.$message.success(`${res.meta.msg}`)
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    setRightsDialogClosed() {
      // 防止暂存权限节点累积叠加
      this.defKeys = []
    },
    // 通过递归获取三级权限的id，一二级会同步勾选所以不用
    getLeafKeys(node, arr) {
      // 如果节点 没有children
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 分配权限的Dialog
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('失败!')
      }
      this.rightsList = res.data
      this.$message.success('成功!')
      // console.log(role)
      // 自定义递归获取选中的所有三级权限的id
      this.getLeafKeys(role, this.defKeys)
      // console.log(this.defKeys)
      this.setRightDialogVisible = true
    },
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      this.rolesList = res.data
      this.$message.success(`${res.meta.msg}`)
    },
    // 删除权限
    removeRightById(role, rightId) {
      //   弹窗
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async confirm => {
          const { data: res } = await this.$http
            .delete(`roles/${role.id}/rights/${rightId}`)
            .catch(err => err)
          console.log('删除操作', res)
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败!')
          }
          this.$message.success(`${res.meta.msg}`)
          // 只刷新children
          role.children = res.data
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    deleteRole(role) {
      console.log(role)
      this.$confirm('确定删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async confirm => {
          const { data: res } = await this.$http
            .delete(`roles/${role.id}`)
            .catch(err => err)
          console.log('删除操作', res)
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败!')
          }
          this.$message.success(`${res.meta.msg}`)
          // 只刷新children
          role.children = res.data
          this.getRolesList()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
